package com.mingzhi.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mingzhi.order.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    /**
     * 解释ObjectMapper 是一个用于将 Java 对象转换为 JSON 的类。
     * 创建一个 ObjectMapper 对象，用于将 R 对象转换为 JSON 字符串。
     */
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       String resourceName,
                       BlockException e) throws Exception {
        // 设置返回的内容类型
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        R r = R.error("500", resourceName + "被 Sentinel 限制了" + e.getMessage());
        String value = objectMapper.writeValueAsString(r);
        writer.write(value);

    }
}
